package com.sr.recitewords.controller;

import cn.hutool.core.lang.UUID;
import com.sr.recitewords.common.vo.GeneralResult;
import com.sr.recitewords.service.redis.RedisService;
import com.sr.recitewords.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/image")
@Api(tags = {"验证图片生成模块"})
public class ImageController extends BaseController {

    @Resource
    private RedisService redisService;

    @ApiOperation(value = "生成四位数的验证码图片")
    @RequestMapping(value = "/getGenerateImage", method = RequestMethod.GET)
    public GeneralResult<HashMap> getGenerateImage() throws IOException {
        HashMap<String, String> map = new HashMap<>();
        String code = VerifyCodeUtils.generateVerifyCode(4);
        System.out.println("生成" + code);
        String key = UUID.randomUUID().toString();
        File image = new File("./img/images.png");
        VerifyCodeUtils.outputImage(220, 60, image, code);
        BufferedImage read = ImageIO.read(image);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(read, "png", bos);
        String s = Base64Utils.encodeToString(bos.toByteArray());
        map.put("key", key);
        map.put("imageBase64", s);
        redisService.setString(key, code, (long) (60 * 60 * 3), TimeUnit.SECONDS);
        return GeneralResult.genSuccessResult(map);
    }


}
